<script setup>
import {computed, getCurrentInstance, ref, watch} from "vue";
import {QueryShopCart, updateShopCart} from "@/api/cart.js"
import {closeToast, showLoadingToast} from "vant";


const {proxy} = getCurrentInstance()


const list = ref([]);

const checkList = computed({
  get() {
    return list.value.filter(item => !item.isCheck).map(item => item.id)
  },
  set(v) {
    list.value.forEach(item => {
      item['isCheck'] = !v.includes(item.id)
    })
  }
})

// 分页下拉配置
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const totalPrice = ref(0);

const total = ref(0)
const params = ref({
  keywords: "",
  page: 1,
  pageSize: 10
})

const checkAll = computed({
  get() {
    return list.value.length === checkList.value.length
  },
  set(v) {
    list.value.forEach(item => {
      item['isCheck'] = !v
    })
  }
})


watch(() => list.value, (val) => {
  totalPrice.value = list.value.reduce((pre, item) => pre + item.goodsNum * item.goodsPrice * !item.isCheck, 0)
  totalPrice.value *= 100
}, {
  deep: true
})


const onLoad = async () => {
  try {
    const res = await QueryShopCart(params.value)
    if (res.data.records || res.data.records) {
      list.value.push(...res.data.records)
      total.value = res.data.total
    }
    if (list.value.length >= total.value) {
      finished.value = true;
    }
    refreshing.value = false
    params.value.page++
  } catch (e) {
    loading.value = false
    finished.value = true
  }
};

const onRefresh = () => {
  // 清空列表数据
  finished.value = false;
  // 重新加载数据
  list.value = []
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true;
  params.value.page = 1
  onLoad();
};

// 提交订单事件
const onSubmit = () => {
  const data = list.value.filter(item => !item.isCheck)
  localStorage.setItem("goods_detail_submit", JSON.stringify(data))
  proxy.$router.push("/order")
}

const changeNumber = async (row, val) => {
  try {
    showLoadingToast({forbidClick: true});
    const params = Object.assign({}, row)
    params.goodsNum = val
    await updateShopCart(params)
    closeToast();
  } catch (e) {
  }
}


</script>

<template>
  <van-nav-bar
      title="购物车"
  />
  <van-search v-model="params.keywords" placeholder="请输入搜索关键词"/>
  <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
        class="list overflow-auto"
        v-model:loading="loading"
        :finished="finished"
        :finished-text="list.length > 0 ?'没有更多了': ''"
        @load="onLoad"
    >
      <template v-if="list.length">
        <van-card
            :price="item.goodsPrice.toFixed(2)"
            :desc="item.goodsNorm"
            :title="item.title"
            :thumb="item.banner"
            v-for="item in list"
            :key="item.id"
        >
          <template #num>
            <van-stepper v-model="item.goodsNum" @plus="changeNumber(item, 1)" @minus="changeNumber(item, -1)"/>
          </template>
          <template #thumb>
            <div class="flex items-center w-full h-full justify-between">
              <van-checkbox-group v-model="checkList">
                <van-checkbox :name="item.id"></van-checkbox>
              </van-checkbox-group>
              <van-image :src="item.banner" class="w-[65%] aspect-[1]">
                <template v-slot:loading>
                  <van-loading type="spinner" size="20"/>
                </template>
              </van-image>
            </div>
          </template>
        </van-card>
      </template>
      <div v-else class=" p-[10px]">
        <van-empty description="空空如也" class="bg-[#fff]"/>
      </div>
    </van-list>
  </van-pull-refresh>
  <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
    <van-checkbox v-model="checkAll">全选</van-checkbox>
  </van-submit-bar>
</template>

<style scoped lang="scss">
.list {
  height: calc(100vh - 165px - 84px);
  background-color: #f4f4f4;
}

.content {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(2, 1fr);
  padding: 10px;
}

.van-submit-bar {
  bottom: 60px;
}
</style>
